const express = require('express')
const { body, validationResult } = require('express-validator')
const boom = require('boom')
const {login, queryOne} = require('../service/user')
const Result = require('../models/Result')
const {md5 , decode} = require('../utils')
const { PWT_SALT } = require('../utils/constant')

const jwt = require('jsonwebtoken')
const { PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')
// const {  querySql } = require('../db')

const router = express.Router()

function findUser(username) {
  const sql = `select * from admin_user where username='${username}'`
  return queryOne(sql)
}

router.get('/info', function(req, res) {
  const decoded = decode(req)
  if (decoded && decoded.username) {
    findUser(decoded.username).then(user => {
      if (user) {
        user.roles = [user.role]
        new Result(user, '获取用户信息成功').success(res)
      } else {
        new Result('获取用户信息失败').fail(res)
      }
    })
  } else {
    new Result('用户信息解析失败').fail(res)
  }
})
router.post('/login',
  [
    body('username').isString().withMessage('username类型不正确'),
    body('password').isString().withMessage('密码必须为数字')
  ],
  function(req, res, next) {
    const err = validationResult(req)
    if (!err.isEmpty()) {
      const [{ msg }] = err.errors
      next(boom.badRequest(msg))
    } 
    else{
      let {username, password } = req.body
      password = md5(`${password}${PWT_SALT}`)
      login(username,password).then(user => {
        if (!user || user.length === 0) {
          new Result('登录失败').fail(res)
        } else {
          const token = jwt.sign(
            { username },
            PRIVATE_KEY,
            { expiresIn: JWT_EXPIRED }
          )
          new Result({ token }, '登录成功').success(res)
        }
      })
      .catch(err =>{
        console.log(err);
      })
      // console.log(req.body);
      // if(username==='admin'&&password=== 'admin'){
      //   new Result("登录成功").success(res)
      // } else{
      //   new Result("登录失败").fail(res)
      // }
    }
  }
)
module.exports = router